<template>
  <div ref="contentContainer">
    <template v-for="(item, index) in content" :key="index">
      <!-- 文本类型 -->
      <TextBlock v-if="item.type === 'text'" :content="item.content" :highlighted="item.highlighted" />
      
      <!-- 卡片类型 -->
      <CardBlock v-if="item.type === 'cards'" :cards="item.cards" />
      
      <!-- 表格类型 -->
      <TableBlock v-if="item.type === 'table'" :table="item.table" />
      
      <!-- 图片类型 -->
      <ImageBlock v-if="item.type === 'image'" :image="item.image" />
      
      <!-- 列表类型 -->
      <ListBlock v-if="item.type === 'list'" :list="item.list" />
      
      <!-- 标题类型 -->
      <h2 
        v-if="item.type === 'heading'" 
        :id="item.id" 
        class="text-2xl font-bold mt-10 mb-4 text-gray-900"
        ref="headingElements"
      >
        {{ item.content }}
      </h2>
      
      <!-- 引用类型 -->
      <blockquote v-if="item.type === 'blockquote'" class="border-l-4 border-primary pl-4 italic my-6 text-gray-700">
        {{ item.content }}
      </blockquote>
    </template>
  </div>
</template>

<script>
import TextBlock from './blocks/TextBlock.vue';
import CardBlock from './blocks/CardBlock.vue';
import TableBlock from './blocks/TableBlock.vue';
import ImageBlock from './blocks/ImageBlock.vue';
import ListBlock from './blocks/ListBlock.vue';

export default {
  name: 'ContentRenderer',
  components: {
    TextBlock,
    CardBlock,
    TableBlock,
    ImageBlock,
    ListBlock
  },
  props: {
    content: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      headingElements: []
    };
  },
  mounted() {
    // 注册滚动监听事件
    window.addEventListener('scroll', this.handleScroll);
    // 初始检查当前可见的标题
    this.checkActiveHeading();
    // 通知父组件内容已渲染完成
    this.$emit('content-rendered');
  },
  beforeUnmount() {
    // 移除滚动监听事件
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    // 处理滚动事件，检查当前可见的标题
    handleScroll() {
      this.checkActiveHeading();
    },
    // 检查当前可见的标题并高亮显示
    checkActiveHeading() {
      const headings = this.content.filter(item => item.type === 'heading');
      const scrollPosition = window.scrollY + 100;
      
      for (let i = headings.length - 1; i >= 0; i--) {
        const heading = document.getElementById(headings[i].id);
        if (heading && heading.offsetTop <= scrollPosition) {
          this.$emit('active-heading-change', headings[i].id);
          break;
        }
      }
    },
    // 滚动到指定的标题
    scrollToHeading(headingId) {
      const heading = document.getElementById(headingId);
      if (heading) {
        window.scrollTo({
          top: heading.offsetTop - 80,
          behavior: 'smooth'
        });
      }
    }
  },
  // 暴露方法给父组件调用
  expose: ['scrollToHeading']
};
</script>

<style scoped>
/* 组件样式可以在这里添加 */
</style>